import { deepClone, resolveRoutePath } from '@/util'
import { systemRoutes } from '@/router/routes'
import { isObject } from 'lodash-es'
import useSettingsStore from './settings'
import useUserStore from './user'

function hasPermission(permissions, route) {
  let isAuth = false
  if (route.meta && route.meta.auth) {
    isAuth = permissions.some(auth => route.meta.auth === auth)
  } else {
    isAuth = true
  }
  return isAuth
}

function filterAsyncRoutes(routes, permissions) {
  const res = []
  routes[0].children.forEach(route => {
    let tmpRoute = deepClone(route)
    if (hasPermission(permissions, tmpRoute)) {
      res.push(tmpRoute)
    }
  })
  return res
}

// 将多层嵌套路由处理成两层，保留顶层和最子层路由，中间层级将被拍平
function flatAsyncRoutes(routes, breadcrumb = [], baseUrl = '', isRoot = true) {
  if (Array.isArray(routes)) {
    routes = routes.filter(route => isObject(route))
  }
  if (isRoot) {
    if (routes.children) {
      routes.children = flatAsyncRoutes(routes.children, [{
        path: routes.path,
        title: routes.meta.title,
        i18n: routes.meta.i18n,
        hide: !routes.meta.breadcrumb && routes.meta.breadcrumb === false
      }], routes.path, false)
    }
    return routes
  } else {
    let res = []
    routes.forEach(route => {
      if (route.children) {
        let childrenBaseUrl = resolveRoutePath(baseUrl, route.path)
        let childrenBreadcrumb = deepClone(breadcrumb)
        if (route.meta.breadcrumb !== false) {
          childrenBreadcrumb.push({
            path: childrenBaseUrl,
            title: route.meta.title,
            i18n: route.meta.i18n,
            hide: !route.meta.breadcrumb && route.meta.breadcrumb === false
          })
        }
        let tmpRoute = deepClone(route)
        tmpRoute.path = childrenBaseUrl
        tmpRoute.meta.breadcrumbNeste = childrenBreadcrumb
        delete tmpRoute.children
        res.push(tmpRoute)
        let childrenRoutes = flatAsyncRoutes(route.children, childrenBreadcrumb, childrenBaseUrl, false)
        childrenRoutes.map(item => {
          // 如果 path 一样则覆盖，因为子路由的 path 可能设置为空，导致和父路由一样，直接注册会提示路由重复
          if (res.some(v => v.path == item.path)) {
            res.forEach((v, i) => {
              if (v.path == item.path) {
                res[i] = item
              }
            })
          } else {
            res.push(item)
          }
        })
      } else {
        let tmpRoute = deepClone(route)
        tmpRoute.path = resolveRoutePath(baseUrl, tmpRoute.path)
        // 处理面包屑导航
        let tmpBreadcrumb = deepClone(breadcrumb)
        tmpBreadcrumb.push({
          path: tmpRoute.path,
          title: tmpRoute.meta.title,
          i18n: tmpRoute.meta.i18n,
          hide: !tmpRoute.meta.breadcrumb && tmpRoute.meta.breadcrumb === false
        })
        tmpRoute.meta.breadcrumbNeste = tmpBreadcrumb
        res.push(tmpRoute)
      }
    })
    return res
  }
}

const useRouteStore = defineStore(
  // 唯一ID
  'route',
  {
    state: () => ({
      isGenerate: false,
      routes: [],
      currentRemoveRoutes: [],
      breadcrumbList: []
    }),
    getters: {},
    actions: {
      flatRoutes() {
        const settingsStore = useSettingsStore()
        let routes = []
        if (this.routes) {
          if (settingsStore.app.routeBaseOn !== 'filesystem') {
            this.routes.map(item => {
              routes.push(...deepClone(item.children))
            })
            routes.map(item => flatAsyncRoutes(item))
          } else {
            this.routes.map(item => {
              routes.push(deepClone(item))
            })
          }
        }
        return routes
      },
      flatSystemRoutes() {
        let routes = []
        systemRoutes.map(item => {
          routes.push(deepClone(item))
        })
        routes.map(item => flatAsyncRoutes(item))
        return routes
      },
      // 根据权限动态生成路由（前端生成）
      generateRoutesAtFront(asyncRoutes) {
        const userStore = useUserStore()
        return userStore.getPermissions().then(res => {
          let accessedRoutes = filterAsyncRoutes(asyncRoutes, res)
          console.log('accessedRoutes', accessedRoutes)
          this.isGenerate = true
          this.routes = asyncRoutes.filter(item => item.children.length != 0 && isObject(item))
          return asyncRoutes
        }).catch(() => {})
      },
      // 记录 accessRoutes 路由，用于登出时删除路由
      setCurrentRemoveRoutes(routes) {
        this.currentRemoveRoutes = routes
      },
      // 清空动态路由
      removeRoutes() {
        this.isGenerate = false
        this.routes = []
        this.currentRemoveRoutes.forEach(removeRoute => {
          removeRoute()
        })
        this.currentRemoveRoutes = []
      },
      // 设置面包屑
      setBreadCrumb(breadCrumb) {
        this.breadcrumbList = breadCrumb
      }
    }
  }
)

export default useRouteStore
